package com.dgut.smart_house.withHardware;

import com.dgut.smart_house.config.WebsocketServer;
import com.dgut.smart_house.domain.Datas;
import com.dgut.smart_house.domain.Device;
import com.dgut.smart_house.domain.Handle;
import com.dgut.smart_house.domain.Types;
import com.dgut.smart_house.mapper.DatasMapper;
import com.dgut.smart_house.mapper.DeviceMapper;
import com.dgut.smart_house.mapper.HandleMapper;
import com.dgut.smart_house.mapper.TypeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
public class WithHardwareSocket extends Thread {


    static Datas data = new Datas();
    ServerSocket server = null;
    Socket socket = null;
    String src = null;


    public WithHardwareSocket() {

        try {
            server = new ServerSocket(10086);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {


        super.run();
        try {

            log.info("等待硬件端连接...");
            socket = server.accept();
            log.info("  硬件端 （" + socket.getInetAddress().getHostAddress() + "） 连接成功...");
            InputStream in = socket.getInputStream();
            int len = 0;
            byte[] buf = new byte[1024];
            src = "硬件端: （" + socket.getInetAddress().getHostAddress() + "）";
            while ((len = in.read(buf)) != -1) {
                log.info(src + "发送："
                        + new String(buf, 0, len, "UTF-8"));
                if(new String(buf, 0, len, "UTF-8").split(":").length==2){
                writeMsg(new String(buf, 0, len, "UTF-8"));}
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            log.info(src + "断开连接");
            this.run();
        }
    }

    /**
     * 写入数据库
     *
     * @param msg
     */
    public static void writeMsg(String msg) {
        String[] str = msg.split(":");

        String command = str[0];
        String msgData=str[1].replaceAll("\r|\n","").replaceAll("0x","").replaceAll("0X","").replaceAll(" ","");
        DataHandling.handling(command,msgData);

    }

    /**
     * 发送消息
     *
     * @param msg
     */
    public void sendMsg(String msg) {
        OutputStream out = null;
        try {
            if (socket != null) {
                out = socket.getOutputStream();
                String in = "";
                in = msg;
                out.write(("" + in).getBytes("UTF-8"));
                out.flush();// 清空缓存区的内容
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}